﻿using DataBase;
using DataBase.DBmodels;
using DataBase.Utils;
using GreenXi.ViewModel;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using ZedGraph;
using Decision = DataBase.Decision;
using Point = System.Windows.Point;

namespace GreenXi.Help.Curve
{
    /// <summary>
    /// 判断框类
    /// zyw 
    /// 2023-9-4
    /// </summary>
    public static class SmoothChart
    {
        // 在类级别定义颜色数组
        private static Color[] colors = new Color[] {
    Color.Red,
    Color.Blue,
    Color.Green,
    Color.Purple,
    Color.Orange,
    Color.Black,
    Color.Red,
    Color.Purple,
    Color.Cyan,
    Color.Magenta,
    Color.Lime,
    Color.Brown,
    Color.Pink,
    Color.Gold,
    Color.Silver,
    Color.Gray,
    Color.DarkRed,
    Color.DarkBlue,
    Color.DarkGreen,
    Color.DarkCyan,
    Color.DarkMagenta,
    Color.DarkOrange,
    Color.LightBlue,
    Color.LightGreen,
    Color.LightPink,
    Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
      Color.LightGreen,
    Color.LightPink,
    Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
        Color.LightGreen,
    Color.LightPink,
    Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
      Color.LightGreen,
    Color.LightPink,
    Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
        Color.Indigo,
    Color.Turquoise,
    Color.Violet,
      Color.LightGreen,
    Color.LightPink,
    Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
        Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
        Color.Indigo,
    Color.Turquoise,
    Color.Violet,
      Color.LightGreen,
    Color.LightPink,
    Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
    Color.Olive,
      Color.LightYellow,
    Color.Indigo,
    Color.Turquoise,
    Color.Violet,
};
        public static void Init(ZedGraphControl zedGraphControl, string PressId, string funcName, List<PointPairList> PairList)
        {
            GraphPane myPane = zedGraphControl.GraphPane;
            myPane.YAxis.Scale.Min = -2;
            myPane.YAxis.Scale.Max = GlobalVariables.GreatestPressure;


            // 设置X轴为日期时间类型
            myPane.XAxis.Type = AxisType.Date;
            // 设置24小时时间格式
            myPane.XAxis.Scale.Format = "HH:mm"; // 24小时制，显示小时:分钟

            // 设置时间范围（示例：一天24小时）
            myPane.XAxis.Scale.Min = new XDate(DateTime.Today); // 00:00
            myPane.XAxis.Scale.Max = new XDate(DateTime.Today.AddDays(1).AddSeconds(-20)); // 23:59:59

            // 设置主要刻度为每3小时
            myPane.XAxis.Scale.MajorStep = 3; // 直接设置为3小时

          

            myPane.Title.Text = "各区域用电总总览";
            myPane.XAxis.Title.Text = "时间(H)";
            myPane.YAxis.Title.Text = "用电量(KWH)";
           
            //设置轴的上下限
            // Show the x axis grid
            myPane.XAxis.MajorGrid.IsVisible = false;
            myPane.XAxis.MinorGrid.IsVisible = false;
            // Make the Y axis scale red
            myPane.YAxis.Scale.FontSpec.FontColor = Color.Red;
            myPane.YAxis.Title.FontSpec.FontColor = Color.Red;
            // turn off the opposite tics so the Y tics don't show up on the Y2 axis
            myPane.YAxis.MajorTic.IsOpposite = false;
            myPane.YAxis.MinorTic.IsOpposite = false;
            myPane.YAxis.MinorTic.IsAllTics = false;
            // Don't display the Y zero line
            myPane.YAxis.MajorGrid.IsVisible = false;
            myPane.YAxis.MinorGrid.IsVisible = false;
            myPane.YAxis.MajorGrid.IsZeroLine = false;
            // 设置X轴的最小刻度间隔为0.5
            myPane.XAxis.Scale.MinorStep = 20;
            // 设置Y轴的最小刻度间隔为0.1
            myPane.YAxis.Scale.MinorStep = 0;

            myPane.YAxis.Scale.MajorStep = GlobalVariables.GreatestPressure/10; 
            // Align the Y axis labels so they are flush to the axis
            myPane.YAxis.Scale.Align = AlignP.Inside;
            zedGraphControl.IsAutoScrollRange = true;
            zedGraphControl.IsScrollY2 = true;
            //是否缩放
            zedGraphControl.IsEnableZoom = true;
            zedGraphControl.IsShowPointValues = true;
            zedGraphControl.AxisChange();

            zedGraphControl.GraphPane.CurveList.Clear();//之前数据清除
            using MyDbContext myDbContext = new MyDbContext();
            //从数据库获取数据加载判断框
            var list = myDbContext.GetDecisionByFuncName(funcName, PressId);

            foreach (var item in list)
            {
                double[] x = { item.X1, item.X2, item.X2, item.X1, item.X1 };
                double[] y = { item.Y1, item.Y1, item.Y2, item.Y2, item.Y1 };
                DecusionType type = new DecusionType();
                #region 判断类型后期从数据库获得
                var decisiontype = myDbContext.GetDecisionType(item.Type);
                if (decisiontype != null)
                {
                    type.BottomType = (DashStyle)decisiontype.Bottom;
                    type.TopType = (DashStyle)decisiontype.Top;
                    type.LeftType = (DashStyle)decisiontype.Left;
                    type.RightType = (DashStyle)decisiontype.Right;
                }
                #endregion
                
                SmoothChartDemo(myPane, x, y, type, item.ID);
            }

        
            for(int i= 0;i < GlobalVariables.CraftViewList.Count;i++)
            {
                if (GlobalVariables.ListPress.Count <=i)
                {
                    GlobalVariables.ListPress.Add(new PointPairList());
                }
                if (GlobalVariables.CraftViewList[i].Type!=null&& GlobalVariables.CraftViewList[i].Type==3)
                {
                    var myCurve = myPane.AddCurve(GlobalVariables.CraftViewList[i].Project, GlobalVariables.ListPress[i], colors[i%20], SymbolType.Diamond);//主曲线显示
                    myCurve.Symbol.IsVisible = false;
                }
            }
            // 创建曲线对象
            zedGraphControl.AxisChange();
        }

        public static void Init2(ZedGraphControl zedGraphControl, CraftView Craft)
        {
            GraphPane myPane = zedGraphControl.GraphPane;
            myPane.YAxis.Scale.Min = -2;
            myPane.YAxis.Scale.Max = GlobalVariables.GreatestPressure;


            // 设置X轴为日期时间类型
            myPane.XAxis.Type = AxisType.Date;
            // 设置24小时时间格式
            myPane.XAxis.Scale.Format = "HH:mm"; // 24小时制，显示小时:分钟

            // 设置时间范围（示例：一天24小时）
            myPane.XAxis.Scale.Min = new XDate(DateTime.Today); // 00:00
            myPane.XAxis.Scale.Max = new XDate(DateTime.Today.AddDays(1).AddSeconds(-20)); // 23:59:59

            // 设置主要刻度为每3小时
            myPane.XAxis.Scale.MajorStep = 3; // 直接设置为3小时



            myPane.Title.Text = Craft.Project;
            myPane.XAxis.Title.Text = "时间(H)";
            myPane.YAxis.Title.Text = "用电量(KWH)";

            //设置轴的上下限
            // Show the x axis grid
            myPane.XAxis.MajorGrid.IsVisible = false;
            myPane.XAxis.MinorGrid.IsVisible = false;
            // Make the Y axis scale red
            myPane.YAxis.Scale.FontSpec.FontColor = Color.Red;
            myPane.YAxis.Title.FontSpec.FontColor = Color.Red;
            // turn off the opposite tics so the Y tics don't show up on the Y2 axis
            myPane.YAxis.MajorTic.IsOpposite = false;
            myPane.YAxis.MinorTic.IsOpposite = false;
            // Don't display the Y zero line
            myPane.YAxis.MajorGrid.IsVisible = false;
            myPane.YAxis.MinorGrid.IsVisible = false;
            myPane.YAxis.MajorGrid.IsZeroLine = false;
            // 设置X轴的最小刻度间隔为0.5
            myPane.XAxis.Scale.MinorStep = 20;
            // 设置Y轴的最小刻度间隔为0.1
            myPane.YAxis.Scale.MinorStep = 0;

            myPane.YAxis.Scale.MajorStep = GlobalVariables.GreatestPressure / 10;

            // Align the Y axis labels so they are flush to the axis
            myPane.YAxis.Scale.Align = AlignP.Inside;
            zedGraphControl.IsAutoScrollRange = true;
            zedGraphControl.IsScrollY2 = true;
            //是否缩放
            zedGraphControl.IsEnableZoom = true;
            zedGraphControl.IsShowPointValues = true;
            zedGraphControl.AxisChange();

            zedGraphControl.GraphPane.CurveList.Clear();//之前数据清除
            using MyDbContext myDbContext = new MyDbContext();


            var i=GlobalVariables.CraftViewList.FindIndex(x => x.Id == Craft.Id);
            var myCurve = myPane.AddCurve(Craft.Project, GlobalVariables.ListPress[i], Color.Red, SymbolType.Diamond);//主曲线显示
            myCurve.Symbol.IsVisible = false;

            // 创建曲线对象
            zedGraphControl.AxisChange();
            zedGraphControl.Refresh();
        }


      
        /// <summary>
        /// 绘制判断框
        /// </summary>
        /// <returns></returns>
        public static void SmoothChartDemo(GraphPane MyPane, double[] x, double[] y, DecusionType type, int id, string Type)
        {
            PointPairList[] listMainChart = new PointPairList[5];
            List<DashStyle> typelist = new List<DashStyle>();
            if (Type == "曲线")
            {
                LineItem curve2 = null;
                listMainChart[0] = new PointPairList();
                listMainChart[0].Add(x, y);
                curve2 = MyPane.AddCurve("", listMainChart[0], Color.Red);
                curve2.Symbol.Fill = new Fill(Color.White);
                curve2.Symbol.IsVisible = false;
                curve2.Line.IsAntiAlias = false;
                return;
            }
            else
            {
                typelist.Add(type.BottomType);
                typelist.Add(type.RightType);
                typelist.Add(type.TopType);
                typelist.Add(type.LeftType);

                LineItem curve = null;


                #region 拆分点
                for (int i = 0; i < 4; i++)
                {
                    listMainChart[i] = new PointPairList();
                    double[] x1 = new double[10];
                    x1[i] = x[i];
                    x1[i + 1] = x[i + 1];
                    double[] y1 = new double[10];
                    y1[i] = y[i];
                    y1[i + 1] = y[i + 1];
                    listMainChart[i].Add(x1[i], y1[i]);
                    listMainChart[i].Add(x1[i + 1], y1[i + 1]);
                }
                #endregion
                for (int i = 0; i < 4; i++)
                {
                    var color = Color.Red;
                    if (typelist[i] == DashStyle.Dot || typelist[i] == DashStyle.DashDotDot || typelist[i] == DashStyle.DashDot)
                    {
                        color = Color.Green;
                    }
                    if (typelist[i] == DashStyle.Custom)//空
                    {
                        continue;
                    }
                    //虚线不画
                    if(typelist[i] == DashStyle.Dash)
                    {
                        continue;
                    }
                    curve = MyPane.AddCurve("", listMainChart[i], color, SymbolType.HDash);
                    curve.Symbol.Fill = new Fill(Color.White);
                    curve.Symbol.Size = 5;
                    curve.Line.StepType = StepType.ForwardStep;
                    curve.Line.Style = typelist[i];
                    //curve.Line.Style = DashStyle.DashDotDot;
                    curve.Link.Title = id.ToString();
                    curve.Line.Width = 2f;
                    curve.Symbol.Size = 1;
                }
            }

        }


        /// <summary>
        /// 绘制判断框
        /// </summary>
        /// <returns></returns>
        public static void SmoothChartDemo(GraphPane MyPane, double[] x, double[] y, DecusionType type, int id)
        {
            PointPairList[] listMainChart = new PointPairList[5];
            List<DashStyle> typelist = new List<DashStyle>();
            typelist.Add(type.BottomType);
            typelist.Add(type.RightType);
            typelist.Add(type.TopType);
            typelist.Add(type.LeftType);

            #region 拆分点
            for (int i = 0; i < 4; i++)
            {
                listMainChart[i] = new PointPairList();
                double[] x1 = new double[10];
                x1[i] = x[i];
                x1[i + 1] = x[i + 1];
                double[] y1 = new double[10];
                y1[i] = y[i];
                y1[i + 1] = y[i + 1];
                listMainChart[i].Add(x1[i], y1[i]);
                listMainChart[i].Add(x1[i + 1], y1[i + 1]);
            }
            #endregion
            LineItem curve = null;

            for (int i = 0; i < 4; i++)
            {
                var color = Color.Red;
                if (typelist[i] == DashStyle.Dot || typelist[i] == DashStyle.DashDotDot || typelist[i] == DashStyle.DashDot)
                {
                    
                    color = Color.Green;
                }
                if (typelist[i] == DashStyle.Custom)//空
                {
                    continue;
                }
                //虚线不画
                if (typelist[i] == DashStyle.Dash)
                {
                    continue;
                }


                curve = MyPane.AddCurve("", listMainChart[i], color, SymbolType.HDash);
                curve.Symbol.Fill = new Fill(Color.White);
                curve.Symbol.Size = 5;
                curve.Line.StepType = StepType.ForwardStep;
                curve.Line.Style = typelist[i];
                //curve.Line.Style = DashStyle.DashDotDot;
                curve.Link.Title = id.ToString();
                curve.Line.Width = 2f;
                curve.Symbol.Size = 1;
            }

            ////画一个框方便点击事件触发
            //BoxObj box = new BoxObj(x[3], y[3], x[1] - x[0], y[2] - y[1],
            //Color.Transparent, Color.Transparent, Color.Transparent);

            //// 将矩形对象添加到图表中
            //MyPane.GraphObjList.Add(box);
            MyPane.Chart.Fill = new Fill(Color.White, Color.LightGray, 45.0F);
        }


        public class DecusionType
        {
            public DashStyle TopType { get; set; }
            public DashStyle BottomType { get; set; }
            public DashStyle LeftType { get; set; }
            public DashStyle RightType { get; set; }
        }

        /// <summary>
        /// 根据曲线是否合格
        /// </summary>
        /// <returns></returns>
        public static bool SmoothChartResult(PointPairList List, List<Decision> decisions)
        {
            bool Result = true;

            #region 根据类型判断是否合格


            foreach (Decision item in decisions)
            {
                if (!Result)//不合格直接返回
                {
                    break;
                }
                switch (item.Type)
                {
                    case "左进右出":
                        Result = ClsJudge.CheckJudge1(List, item.X1, item.X2, item.Y1, item.Y2);
                        break;
                    case "左进上出":
                        Result = ClsJudge.CheckJudge2(List, item.X1, item.X2, item.Y1, item.Y2);
                        break;
                    case "下进上出":
                        Result = ClsJudge.CheckJudge7(List, item.X1, item.X2, item.Y1, item.Y2);
                        break;
                    case "最大力":
                        Result = ClsJudge.CheckJudge3(List, item.X1, item.X2, item.Y1, item.Y2);
                        break;
                    case "最大位移":
                        Result = ClsJudge.CheckJudge5(List, item.X1, item.X2, item.Y1, item.Y2);
                        break;
                    case "最大拐点":
                        Result = ClsJudge.CheckJudge6(List, item.X1, item.X2, item.Y1, item.Y2);
                        break;
                }
            }
            #endregion  



            return Result;
        }

        private static bool DoSegmentsIntersect(Point a, Point b, Point c, Point d)
        {
            double denominator = (b.X - a.X) * (d.Y - c.Y) - (b.Y - a.Y) * (d.X - c.X);

            if (denominator == 0)
            {
                return false; // 线段平行或重叠
            }
            double numerator1 = (a.Y - c.Y) * (d.X - c.X) - (a.X - c.X) * (d.Y - c.Y);
            double numerator2 = (a.Y - c.Y) * (b.X - a.X) - (a.X - c.X) * (b.Y - a.Y);
            if (numerator1 == 0 || numerator2 == 0)
            {
                return false; // 线段之一的起点或终点在另一条线段上
            }
            double r = numerator1 / denominator;
            double s = numerator2 / denominator;
            if (r >= 0 && r <= 1 && s >= 0 && s <= 1)
            {
                return true; // 交点在两条线段内部
            }

            return false;
        }
    }
}